<?php

class ContactController extends BaseController {

    const MODEL_CLASS_NAME = 'Contact';

    public function actionIndex() {
	$model = new Contact();
	$refreshCaptcha = true;
	if (isset($_POST[self::MODEL_CLASS_NAME])) {
	    $refreshCaptcha = true;
	    $model->attributes = $_POST[self::MODEL_CLASS_NAME];

    	    if ($model->validate()) {
		Yii::app()->user->setState($this->id . '-flag', true);

		if ($model->save(true)) {
		    //DONE:  Sending email to webmaster, requrester and relating people
		    $to = Yii::app()->params['email']['admin'];
		    //If debug mode is true, send email for tester
		    if (param("debugMode") == true) {
			$to = param('emailTesting');
		    }

		    $subjectToWebmaster = t('EMAIL_TO_MANAGER_SUBJECT', 'contact');
		    $bodyToWebmaster = t('EMAIL_TO_MANAGER_BODY', 'contact', array(
			'{NAME}' => $model->name,
			'{EMAIL}' => $model->email,
			'{COMPANY}' => $model->company,
			'{PHONE}' => $model->phone,
			'{ROLE}' => $model->role,
			'{COMMENT}' => $model->comment,
		    ));

		    sendMail($to, $bodyToWebmaster, $subjectToWebmaster);

		    //Send email to user
		    $subjectToUser = t('EMAIL_TO_REGISTER_SUBJECT', 'contact');
		    $bodyToUser = t('EMAIL_TO_REGISTER_BODY', 'contact', array(
			'{NAME}' => $model->name,
		    ));

		    $toRequester = $model->email;

		    //If debug mode is true, send email for tester
		    if (param("debugMode") == true) {
			$toRequester = param('emailTesting');
		    }

		    sendMail($toRequester, $bodyToUser, $subjectToUser);
		    $this->redirect(url($this->id . '/thanks')
		    );
		}
	    }
	}


	$this->render('index', array(
	    'model' => $model,
	    'refreshCaptcha' => $refreshCaptcha));
    }

    function actionThanks() {
	if (Yii::app()->user->getState($this->id . '-flag')) {
	    $this->render('thanks');
	} else {
	    $this->redirect(url($this->id . '/index'));
	}
    }

    function actions() {
	return array(
	    'captcha' => array(
		'class' => 'CaptchaAction',
		'maxLength' => 4,
		'minLength' => 4,
		'testLimit' => 2,
	    ),
	);
    }
}

